import { useUser } from './../stores/userStore';
import { boot } from 'quasar/wrappers';
import axios, { AxiosInstance } from 'axios';
import { LoadingBar, Notify } from 'quasar';
import { createRouter, createWebHistory, useRouter } from 'vue-router';
import { Dialog } from 'quasar';
import { useQuasar,Loading } from 'quasar'
import UnauthorizedDialog from 'src/components/UnauthorizedDialog.vue'
const router = useRouter();
const $q = useQuasar()
declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $axios: AxiosInstance;
  }
}

// console.log(process.env.BUILD_ENV)

export function resolveFrontendUrl() {
  if (process.env.DJANGO_URL && process.env.DJANGO_URL != '') {
    return process.env.DJANGO_URL;
  } else {
    return `${window.location.protocol}//${window.location.hostname}:9000`;
  }
}

export function resolveDjangoUrl() {
  // console.log(process.env.DJANGO_URL)
  if (process.env.DJANGO_URL && process.env.DJANGO_URL != '') {
    return process.env.DJANGO_URL;
  } else {
    return `${window.location.protocol}//127.0.0.1:8001`;  }
}
// Be careful when using SSR for cross-request state pollution
// due to creating a Singleton instance here;
// If any client changes this (global) instance, it might be a
// good idea to move this instance creation inside of the
// "export default () => {}" function below (which runs individually
// for each client)
const api = axios.create({ baseURL: resolveDjangoUrl() });

export interface IDjangoFieldError {
  [key: string]: string[];
}

function isDjangoFieldError(v: any): boolean {
  return Array.isArray(v);
}

export default boot(({ app }) => {
  // for use inside Vue files (Options API) through this.$axios and this.$api

  api.interceptors.request.use((config) => {
    const user = useUser();
    if (!user.isLogin) {
      user.load();
    }
    if (user.isLogin) {
      config.headers.Authorization = 'Token ' + user.token;
      console.log(config.headers.Authorization);
    }

    // Loading.hide()
    LoadingBar.start();
    return config;
  });

  api.interceptors.response.use(
    (response) => {
      LoadingBar.stop();
      return response;
    },
    (error) => {
      LoadingBar.stop();

      if (error.response) {
        const { response } = error;

        // if (response.status == 401){
        //   Dialog.create({
        //     title:'Unauthorized',
        //     message:'Session expired, Please login again',
        //     persistent:true
        //   }).onOk(()=>{
        //     const user = useUser()
        //     user.logout()
        //     router.push({name:'login'})
        //   })
        //   return Promise.reject(error);
        // }
        if(response.status==500) return Promise.reject(error);
        if(response.status==400) return Promise.reject(response.data);
        if (
          response.status &&
          response.status >= 400 &&
          response.status <= 599
        ) {
          const messages = [];

          if (response.data?.error) {
            messages.push(response.data.error);
          }
          if (response.data?.message) {
            messages.push(response.data.message);
          }

          // django form error
          // non filed error
          if (response.data?.non_field_errors) {
            messages.push(...response.data.non_field_errors);
          }
          // field errors
          if (Object.keys(response.data).length > 0) {
            for (const k in response.data) {
              if (k != 'non_field_errors') {
                const m = response.data[k];
                if (isDjangoFieldError(m)) {
                  messages.push(`${k}: ${m.join(' ')}`);
                }
              }
            }
          }

          if (messages.length == 0) {
            messages.push(`${response?.status}: ${response?.statusText}`);
          }

          Notify.create({
            message: messages.join(' '),
            color: 'negative',
            actions: [
              {
                label: 'OK',
                class: 'text-white',
              },
            ],
          });
          console.log(messages);
          
          if (messages[0].includes('Insufficient permission')&&response.data.notice) {
            console.log(response.data.notice);
            
            Dialog.create({
              component:UnauthorizedDialog,
              componentProps: {
                text: response.data.notice,
                // ...more..props...
              },
              // class:'notice-dialog',
              // maximized: true,
              title: 'Unauthorized',
              message: response.data.notice,
              persistent: true,
            }).onOk(async () => {
              window.location.href = '/'
            });
          }
          Loading.hide()
        }
      }
      return Promise.reject(error);
    }
  );

  app.config.globalProperties.$axios = axios;
  // ^ ^ ^ this will allow you to use this.$axios (for Vue Options API form)
  //       so you won't necessarily have to import axios in each vue file

  app.config.globalProperties.$api = api;
  // ^ ^ ^ this will allow you to use this.$api (for Vue Options API form)
  //       so you can easily perform requests against your app's API
});


export { api };
